package com.weixing.mall.provider.support.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.weixing.mall.provider.model.domain.Goods;
import com.weixing.mall.provider.model.domain.GoodsIntro;
import com.weixing.mall.provider.model.domain.PhotoGallery;
import com.weixing.mall.provider.model.enums.GoodsFromEnum;
import com.weixing.mall.provider.service.IGoodsIntroService;
import com.weixing.mall.provider.service.IGoodsService;
import com.weixing.mall.provider.service.IPhotoAlbumService;
import com.weixing.mall.provider.service.IPhotoGalleryService;
import com.weixing.mall.util.ThreadLocalMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PhotoAlbumDataListener extends AnalysisEventListener<PhotoAlbumData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(PhotoAlbumData.class);
    /**
     * 每隔500条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 500;
    List<PhotoAlbumData> list = new ArrayList<PhotoAlbumData>();
    @Autowired
    private IPhotoGalleryService photoGalleryService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsIntroService goodsIntroService;



    public PhotoAlbumDataListener() {
    }

    @Autowired
    public PhotoAlbumDataListener(IPhotoGalleryService photoGalleryService,IGoodsService goodsService,IGoodsIntroService goodsIntroService) {
        this.photoGalleryService = photoGalleryService;
        this.goodsService = goodsService;
        this.goodsIntroService = goodsIntroService;
    }

    @Override
    public void invoke(PhotoAlbumData data,AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始查询数据！", list.size());
        Map<String,List<String>> tt=new HashMap<String,List<String>>();
        for(int i=0;i<list.size();i++){
            String goodsn=  list.get(i).getGoodsSn();
            List<String> tmp= Lists.newArrayList();
            if(i==(list.size()-1)){
                tmp.add(list.get(i).getImgName());
                tt.put(goodsn,tmp);
            }
            for(int j=i+1;j<list.size();j++){
                String checkSn=list.get(j).getGoodsSn();
                if(goodsn.equals(checkSn)){
                    tmp.add(list.get(j).getImgName());
                    list.remove(j);
                    j--;
                }
                tt.put(goodsn,tmp);
            }

        }

        for(Map.Entry<String, List<String>> entry:tt.entrySet()){
            StringBuffer buffer=new StringBuffer();
            Goods goods=goodsService.checkGoods(entry.getKey(),null);
            Long goodId=0L;
            if(goods==null){
                Goods insertgoods=new Goods();
                insertgoods.setGoodsSn(entry.getKey());
                insertgoods.setGoodsFrom(GoodsFromEnum.EXCEL.getValue());
                goodsService.save(insertgoods);
                goodId=insertgoods.getId();
            }else{
                goodId=goods.getId();
            }
            GoodsIntro goodsIntro= goodsIntroService.getOne(new QueryWrapper<GoodsIntro>().eq("goods_id",goodId));
            buffer.append("<p>");
            for(String  ss: entry.getValue()){
                buffer.append("<img class=\"wscnph\" src=\"http://lmpic.weixingshishang.cn/"+ss+"\" />");
            }
            buffer.append("</p>");
            if(null!=goodsIntro){

                goodsIntro.setGoodsIntro(buffer.toString());
                goodsIntroService.updateById(goodsIntro);
            }else{
                GoodsIntro intro=new GoodsIntro();
                intro.setGoodsId(goodId);
                intro.setGoodsIntro(buffer.toString());
                goodsIntroService.save(intro);
            }

        }

    }
}